package com.hs.communication.common.fallback.handlers;

import com.hs.common.core.constant.SecurityConstants;
import com.hs.communication.common.entity.UpsData;
import com.hs.communication.common.feign.RemoteUpsService;
import com.hs.communication.common.utils.ByteBuffer;
import com.hs.communication.common.utils.ByteUtil;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;

import static com.hs.communication.common.constant.Code.*;

@Component
public class UpsHandler {
    public Map<Byte, BiConsumer<String, byte[]>> map = new HashMap<>();

    @PostConstruct
    public void init() {
        map.put(LOGIN, this::handle0x01);
        map.put(HEARTBEAT, this::handle0x03);
        map.put(REAL_DATA, this::handle0x11);
    }

    @Resource
    private RemoteUpsService remoteUpsService;

    /**
     * 假设一帧协议格式如下
     * * 帧头   设备类型 功能码 帧码   数据长度 数据内容 crc校验
     * * 0x10  1字节   1字节  2字节  2字节    n字节   2字节
     *
     * @param bytes
     */
    public void handle0x01(String connection, byte[] bytes) {
        ByteBuffer buffer = ByteBuffer.wrap(bytes);
        byte[] prefix = buffer.getBytes(7); //一条数据的固定前缀,后面的才是真正的数据
        byte[] sn_bytes = buffer.getBytes(7);
        byte[] vol_in_bytes = buffer.getBytes(2);
        byte[] vol_out_bytes = buffer.getBytes(2);
        byte[] cur_in_bytes = buffer.getBytes(2);
        byte[] cur_out_bytes = buffer.getBytes(2);
        byte[] fre_in_bytes = buffer.getBytes(2);
        byte[] fre_out_bytes = buffer.getBytes(2);


        String sn = ByteUtil.bytesToStr(sn_bytes);
        double vol_in = ByteUtil.bytesToInt(vol_in_bytes) / 10.0;
        double vol_out = ByteUtil.bytesToInt(vol_out_bytes) / 10.0;
        double cur_in = ByteUtil.bytesToInt(cur_in_bytes) / 10.0;
        double cur_out = ByteUtil.bytesToInt(cur_out_bytes) / 10.0;
        double fre_in = ByteUtil.bytesToInt(fre_in_bytes) / 10.0;
        double fre_out = ByteUtil.bytesToInt(fre_out_bytes) / 10.0;

        System.out.println("sn=" + sn);
        System.out.println("vol_in=" + vol_in);
        System.out.println("vol_out=" + vol_out);
        System.out.println("cur_in=" + cur_in);
        System.out.println("cur_out=" + cur_out);
        System.out.println("fre_in=" + fre_in);
        System.out.println("fre_out=" + fre_out);

        UpsData upsData = UpsData.builder().sn(sn).connection(connection).reportTime(LocalDateTime.now()).voltageInput(vol_in).voltageOutput(vol_out).currentInput(cur_in)
                .currentOutput(cur_out).frequencyInput(fre_in).frequencyOutput(fre_out).build();

        remoteUpsService.insert(upsData, SecurityConstants.INNER);
    }

    public void handle0x03(String connection, byte[] bytes) {

    }

    public void handle0x11(String connection, byte[] bytes) {

    }
}
